import { useAccessStore, useUserStore } from '@vben/stores';

import { message } from 'ant-design-vue';
import { defineStore } from 'pinia';

import { getCaptchaImage, getUserInfoApi,getUserRoutesApi, userLogin } from '#/api';
import { router } from '#/router';
import { DEFAULT_HOME_PATH } from '@vben/constants';
import { resetAllStores } from '@vben/stores';
import { logoutApi } from '#/api'; 
/*
export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);


  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;
      const {
        data: { token: accessToken },
      } = await userLogin(params);

      // 如果成功获取到 accessToken
      if (accessToken) {
        accessStore.setAccessToken(accessToken);

        // 获取用户信息并存储到 accessStore 中
        const [fetchUserInfoResult, accessCodes] = await Promise.all([
          fetchUserInfo(),
          getAccessCodesApi(),
        ]);

        userInfo = fetchUserInfoResult;

        userStore.setUserInfo(userInfo);
        accessStore.setAccessCodes(accessCodes);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          onSuccess
            ? await onSuccess?.()
            : await router.push(userInfo.homePath || DEFAULT_HOME_PATH);
        }

        if (userInfo?.realName) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
            duration: 3,
            message: $t('authentication.loginSuccess'),
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  async function fetchUserInfo() {
    let userInfo: null | UserInfo = null;
    userInfo = await getUserInfoApi();
    userStore.setUserInfo(userInfo);
    return userInfo;
  }

  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
  };
});
*/
// const accessStore = useAccessStore();
// const userStore = useUserStore();
// const router = useRouter();
export const useAuthStore = defineStore('auth', {
  state: () => ({
    loginLoading: false,
    captcha: {
      image: '',
      uuid: '',
    },
  }),
  actions: {
    async refreshCaptchaImage() {
      const {
        data: { img, uuid },
      } = await getCaptchaImage();
      this.captcha.image = `data:image/png;base64,${img}`;
      this.captcha.uuid = uuid;
      // .then((res) => {
      //   console.log(res);
      //   captchaImage.value = `data:image/png;base64,${res.data.img}`;
      //   userRegisterData.uuid = res.data.uuid;
      // })
      // .catch((error) => {
      //   console.log(error);
      // });
    },
    async authLogin(
      params: Parameters<typeof userLogin>[0],
      onSuccess?: () => Promise<void> | void,
    ) {
      this.loginLoading = true;
      const {
        data: { token, code, msg },
      } = await userLogin(params);
      if (code === 200) {
        message.success('登陆成功！');
        console.log(token);
        const accessStore = useAccessStore();
        const userStore=useUserStore()
        accessStore.setAccessToken(token);
        //获取用户信息
        // const data = await getUserInfoApi();
        const [data1,data2] =await Promise.all([getUserInfoApi(),getUserRoutesApi()])
        //获取用户路由列表
        console.log(data1,data2);
        router.push(DEFAULT_HOME_PATH)
        // onSuccess
        //     ? await onSuccess?.()
        //     : await router.push(userInfo.homePath || DEFAULT_HOME_PATH);
      }
      if (code === 500) {
        message.error(msg);
        this.refreshCaptchaImage();
      }
      // if (token) {
      //   const accessStore = useAccessStore();
      //   accessStore.setAccessToken(token);
      //   const data = await getUserInfoApi();
      //   console.log(data);
      // }
    },
    // async loginOut() {
      async logout(redirect: boolean = true) {
        try {
          await logoutApi();
        } catch {
          // 不做任何处理
        }
        resetAllStores();
        const accessStore=useAccessStore()
        accessStore.setLoginExpired(false);
    
        // 回登录页带上当前路由地址
        await router.replace({
          path:'/auth/login',
          query: redirect
            ? {
                redirect: encodeURIComponent(router.currentRoute.value.fullPath),
              }
            : {},
        });
      },
    // },
    async fetchUserInfo() {},
    $reset() {},
  },
});
